#include "inc.h"

#define TAG_CLIENT "CLIENT"

bool client(const char *hostname, uint16_t port, void *udata
    , std::function<bool(SOCKET fd, void *udata)> callback) {
  if (!hostname || ! callback) return false;
  bool ret = false;
  sockaddr_in addr = { 0 };
  SOCKET fd = 0;
  hostent *p = 0;

  fd = socket(AF_INET, SOCK_STREAM, 0);
  if (fd < 0) {
    MY_LOG(TAG_CLIENT, "create socket error.");
    goto lb_err;
  }

  addr.sin_addr.s_addr = 0;
	addr.sin_port = htons(0);
	addr.sin_family = AF_INET;
	if (bind(fd, (const sockaddr*)&addr, sizeof(addr)) != NOERROR) {
    MY_LOG(TAG_CLIENT, "bind error.");
    goto lb_err;
  }

	p = gethostbyname(hostname);
  if (!p) {
    MY_LOG(TAG_CLIENT, "gethostbyname error.");
    goto lb_err;
  }

  addr.sin_family = p->h_addrtype;
  addr.sin_addr.s_addr = *(u_long*)(p->h_addr_list[0]);
  addr.sin_port = htons(port);

  if (connect(fd, (sockaddr*)&addr, sizeof(addr)) != NOERROR) {
    MY_LOG(TAG_CLIENT, "connect error.");
    goto lb_err;
  }

  MY_LOG(TAG_CLIENT, "connect ok: %s:%d.", hostname, port);

  if (callback)
    ret = callback(fd, udata);

  ret = true;
 lb_err:
  if (fd) closesocket(fd);
  return ret;
}
